package com.imdroid.notification;

import java.util.HashMap;
import java.util.Map;

import com.sun.grizzly.comet.CometContext;

/**
 * The pool of connections
 * 
 */
public class ClientPool {
	/**
	 * The pool of connections
	 */
	public static Map<Integer, CometContext> clients;
	/**
	 * The single instance
	 */
	private static ClientPool instance;

	/**
	 * Private constructor
	 */
	private ClientPool() {

	}

	/**
	 * Get the default connection client pool.
	 * 
	 * @return
	 */
	public static ClientPool getInstance() {
		if (instance == null) {
			instance = new ClientPool();
			clients = new HashMap<Integer, CometContext>();

		}
		return instance;
	}

	/**
	 * Add the client
	 * 
	 * @param userId
	 *            The id of user
	 * @param client
	 *            the http client to write message
	 */
	public void add(int userId, CometContext client) {
		clients.put(userId, client);
	}

	/**
	 * remove the client
	 * 
	 * @param userId
	 *            the id of user
	 */
	public void remove(int userId) {
		clients.remove(userId);
	}

	/**
	 * Get the client by id of user
	 * 
	 * @param userId
	 *            the id of user
	 * @return the target client
	 */
	public CometContext find(int userId) {
		return clients.get(userId);
	}

	/**
	 * Get the count of clients in pool
	 * 
	 * @return the count of clients in pool
	 */
	public int count() {
		return clients.size();
	}

	/**
	 * Check if the user is connected
	 * 
	 * @param userId
	 * @return
	 */
	public boolean isConnected(int userId) {
		return clients.containsKey(userId);
	}

	/**
	 * Get the clientss
	 * 
	 * @return all the clients
	 */
	public Map<Integer, CometContext> getClients() {
		return clients;
	}
}
